/**
 * 发布管理页面路由
 */

var router = require('express').Router();
var assertAlljs = require('../bin/util/assert-alljs');
var dbentityTool = require('../bin/dbentity');
var ObjectID = require('mongodb').ObjectID;
var userTool = require('../bin/user');
var articleTool = require('../bin/article');
var datetimeTool = require('../bin/util/datetime');

router.get('/publishaudit(.*)?', async function(req, res){
    let ses = req.session;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(ses.user, {role:['admin', 'admin:'+res.locals.blockRoot]})))
        return;

    let audits = [];
    let cols = ['article', 'comment', 'feedback'];
    if (req.query.cols!=null){
        if (req.query.cols === ''){
            res.render('dyn.publishaudit.html', { audits });
            return;
        }
        cols = req.query.cols.split(',');
    }

    let article_ids = [];
    let t = (new Date().getTime()) - 12 * 3600000;

    for (let col of cols){
        let filter = {};
        filter[col === 'article' ? 'modifyTime' : 'produceTime']={$gt : t};
        let docs = await dbentityTool.find(col, filter);
        if (await assert(docs instanceof Error))
            return;
        for (let doc of docs){
            let article_id = doc[col === 'article' ? '_id' : 'article_id'];
            let user = doc.produceUser;
            if (col === 'article' && doc.modify.length>1){
                let tmp = await dbentityTool.findOne('user', {_id:ObjectID(doc.modify[doc.modify.length-1][0])});
                if (!(tmp instanceof Error) && tmp != null)
                    user = userTool.getProfile(tmp);
            }

            audits.push({
                produceUser: doc.produceUser,
                produceTime: (col === 'article' ? doc.modifyTime : doc.produceTime),
                produceArticle: (col === 'article' ? doc._id : doc.article_id),
                type : (col === 'feedback' ? doc.type : col),
                path: (col === 'article' ? '' : doc.path),
                brief: (col == 'feedback' ? doc.relate_content + '<p>———— ' + doc.type + ' ————</p>' + doc.description : doc.brief)
            });
            article_ids.push({_id:ObjectID(article_id)});
        }
    }

    if (article_ids.length <= 0){
        res.render('dyn.publishaudit.html', { audits });
        return;
    }

    // 获取根板块所有文章列表
    let appendFilter = {};
    if (res.locals.blockRoot)
        appendFilter.mainclass = { $regex: '^'+res.locals.blockRoot+'(/.*)?$' };
    appendFilter.$or = article_ids;

    let articles = await dbentityTool.find('article', appendFilter);
    if (await assert(articles instanceof Error))
        return;

    let articleDic = {};
    articles.forEach(article=>articleDic[article._id]=article);
    audits = audits.filter(audit=>audit.produceArticle in articleDic); // 去掉非当前版块的文章

    audits.forEach(audit=>audit.produceArticle = articleTool.getProfile(articleDic[audit.produceArticle]));

    audits.sort((p1, p2)=>p2.produceTime-p1.produceTime);
    audits.forEach(audit=>{ audit.produceTime = datetimeTool.to_yMdHm(audit.produceTime, '-', ' ', ':');});

    res.render('dyn.publishaudit.html', { audits, typemap:{article: '文章', comment: '评论', accusation: '举报', feedback: '反馈', advise: '建议'} });
});

module.exports = router;